`
if [[ "${VARIABLE_ONE}" -gt "${VARIABLE_TWO}" ]]; then
echo "${VARIABLE_ONE} is greater than ${VARIABLE_TWO}"
else
echo "${VARIABLE_ONE} is less than ${VARIABLE_TWO}"
fi
We create two variables, VARIABLE_ONE and VARIABLE_TWO, and assign
them values of 10 and 20, respectively. We then use the -gt operator to compare
the two values and print the one that is greater. This script is available at
https://github.com/dolevf/Black-Hat-
Bash/blob/master/ch02/integer_comparison.sh.
Linking Conditions
So far, we’ve used if to check whether a single condition is met. But like
most programming languages, we can also use the or (||) and and (&&) operators
to check for multiple conditions at once.
For example, what if we wanted to check that a file exists and also that its size
greater than zero? Listing 2-4 does so.
#!/bin/bash
echo "Hello World!" > file.txt
if [[ -f "file.txt" ]] && [[ -s "file.txt" ]]; then
echo "The file exists and its size is greater than zero".
fi
Listing 2-4
Chaining two file-test conditions using an and condition
This code writes some content to a file, then checks whether that file exists
and whether its size is greater than zero. Both conditions have to be met in order
for the echo command to be executed. If either returns false, nothing will happen.
To demonstrate an or condition, Listing 2-5 checks whether a file is either of
file or directory type:
#!/bin/bash
DIR_NAME="dir_test"
mkdir "${DIR_NAME}"
if [[ -f "${DIR_NAME}" ]] || [[ -d "${DIR_NAME}" ]]; then
echo "${DIR_NAME} is either a file or a directory."
fi
Listing 2-5
Chaining two file test conditions using or
This code first creates a directory, then uses an if condition with the or (||)
operator to check whether the variable is a file (-f) or directory (-d). The second
condition should evaluate to true, and the echo command should execute.
Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks